using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entidad;
using Dao;
using System.IO;


public partial class ABMAlumno : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Usuario u = Session["login"] as Usuario;
            if (u.tipoUsuario != "Administrador")
                Response.Redirect("~/Login.aspx");
        }
    }
    protected void Page_PreRenderComplete(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lstCarrera.Items.Insert(0, "Seleccione una");
            lstProvincia.Items.Insert(0, "Seleccione una");
            if (Request.QueryString.Count > 0)
            {
                if (Request.QueryString["update"].ToString() == "true")
                {
                    tituloForm.InnerText = "Modificar Alumno";
                    btnNuevo.Visible = false;
                    lbMatricula.Visible = true;
                    rblMatricula.Visible = true;
                    gvAlumno.Visible = true;
                    cvDni.Enabled = false;
                    CargarGrilla();
                }

            }
            else
            {
                lbMatricula.Visible = false;
            }
        }
    }
    private void CargarGrilla()
    {
        try
        {
            gvAlumno.DataSource = AlumnoDao.ObtenerTodoGrilla();
            gvAlumno.DataKeyNames = new string[] { "legajo" };
            gvAlumno.DataBind();
        }
        catch (ApplicationException ex)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "keyhere", "alert('Eror al cargar la tabla de alumnos, debido a: \n " + ex.Message + "');", true);
        }
    }
    private void LimpiarControles()
    {
        txtNombre.Text = string.Empty;
        txtApellido.Text = string.Empty;
        txtDireccion.Text = string.Empty;
        txtNumCalle.Text = string.Empty;
        txtDepto.Text = string.Empty;
        txtBarrio.Text = string.Empty;
        txtTelefono.Text = string.Empty;
        lstCarrera.SelectedIndex = 0;
        txtCp.Text = string.Empty;
        rblMatricula.Items[0].Selected = true;
        lstProvincia.SelectedIndex = 0;
        txtDni.Text = string.Empty;
        ViewState["Legajo"] = null;
    }
    protected void btnNuevo_Click(object sender, EventArgs e)
    {
        this.LimpiarControles();
    }
    protected void btnGrabar_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Alumno a = new Alumno();
            a.apellido = txtApellido.Text;
            a.nombre = txtNombre.Text;
            a.direccion = txtDireccion.Text;
            a.numCalle = int.Parse(txtNumCalle.Text);
            a.depto = txtDepto.Text;
            a.barrio = txtBarrio.Text;
            a.telefono = Int64.Parse(txtTelefono.Text);
            a.codCarrera = int.Parse(lstCarrera.SelectedValue);
            a.cp = int.Parse(txtCp.Text);
            a.estadoAcademico = rblMatricula.Items[0].Selected;
            a.codProvincia = int.Parse(lstProvincia.SelectedValue);
            a.pass = txtDni.Text;
            a.dni = int.Parse(txtDni.Text);
                if (!Request.QueryString.HasKeys())
                {
                    try
                    {
                        AlumnoDao.Insertar(a);
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "keyhere", "alert('Se cargo con exito el alumno " + a.apellido + ", " + a.nombre + " y el legajo que se le asigno es: " + a.legajo + ".');", true);
                        this.LimpiarControles();
                    }catch(ApplicationException aex){
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "keyhere", "alert('Eror al cargar el alumno. \n" + aex.Message + "');", true);
                    }
                }
                else
                {
                    try
                    {
                        a.legajo = int.Parse(ViewState["Legajo"].ToString());
                        AlumnoDao.Actualizar(a);
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),"keyhere", "alert('Se actualizo con exito el alumno " + a.apellido + ", " + a.nombre + ".');", true);
                        this.LimpiarControles();
                        this.CargarGrilla();
                    }
                    catch (ApplicationException aex)
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "keyhere", "alert('Eror al actualizar el alumno. \n" + aex.Message + "');", true);
                    }
                }
        }
    }
    protected void btnEliminar_Click(object sender, EventArgs e)
    {
        if (ViewState["Legajo"] != null)
        {
            AlumnoDao.Eliminar((int)ViewState["Legajo"]);
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "keyhere", "alert('Se elimino con exito el alumno con legajo " + ViewState["Legajo"].ToString() + ".');", true);
            btnNuevo_Click(null, null);
            CargarGrilla();
        }
    }
   

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = AlumnoDao.ValidarDNI(int.Parse(txtDni.Text));
    }
    protected void txtDni_TextChanged(object sender, EventArgs e)
    {
        cvDni.IsValid = AlumnoDao.ValidarDNI(int.Parse(txtDni.Text));
    }

    protected void gvAlumno_SelectedIndexChanged(object sender, EventArgs e)
    {
        ViewState["Legajo"] = gvAlumno.SelectedDataKey.Value.ToString();
        Alumno alu = AlumnoDao.ObtenerPorId(int.Parse(gvAlumno.SelectedDataKey.Value.ToString()));
        txtApellido.Text = alu.apellido;
        txtNombre.Text = alu.nombre;
        txtDni.Text = Convert.ToString(alu.dni);
        txtDireccion.Text = alu.direccion;
        txtNumCalle.Text = Convert.ToString(alu.numCalle);
        txtDepto.Text = alu.depto;
        txtBarrio.Text = alu.barrio;
        txtTelefono.Text = Convert.ToString(alu.telefono);
        txtCp.Text = Convert.ToString(alu.cp);
        lstCarrera.SelectedValue = Convert.ToString(alu.codCarrera);
        lstProvincia.SelectedValue = Convert.ToString(alu.codProvincia);
        if(alu.estadoAcademico)
            rblMatricula.SelectedValue = "1";
        else
            rblMatricula.SelectedValue = "0";
    }
}